<?php

namespace app\api\controller\product;

use app\api\controller\Api;
use app\common\product\model\StoreBanner as BannerModel;
use app\common\product\validate\BannerValidate;
use util\Format;

class Banner extends Api
{
    public function index(){
        $post = $this->request->post();

        $where = [];
        // 获取field
        if (isset($post['keyword']) && !empty($post['keyword'])) $where[] = ['title', 'like', "%{$post['keyword']}%"];

        $model = new BannerModel();
        list($cfg) = Format::pagination($post);
        $pg = $model->where($where)->order('sort,id')->paginate($cfg);
        $rows = $pg->getCollection();

        $result['list'] = $rows;
        $result['pagination'] = Format::pgResult($pg);

        return success($result, '获取数据成功');
    }

    // create
    public function create()
    {
        $post = $this->request->post();
        $validate = new BannerValidate();
        if (!$validate->scene('create')->check($post)) return error([],$validate->getError());

        $model = new BannerModel();
        $model->save($post);

        return success($model->id, '创建成功');
    }

    // update
    public function update()
    {
        $post = $this->request->post();
        $validate = new BannerValidate();
        if (!$validate->scene('update')->check($post)) return error([],$validate->getError());

        $model = new BannerModel();
        $model->update($post, ['id' => $post['id']]);

        return success($model->id, '更新成功');
    }

    public function delete()
    {
        $post = $this->request->post();
        $validate = new BannerValidate();
        if (!$validate->scene('delete')->check($post)) return error([],$validate->getError());

        $model = new BannerModel();
        $model->delete($post['id']);

        return success($model->id, '删除成功');
    }
}